var util = require('../../utils/util.js');
var api = require('../../config/api.js');
const pay = require('../../services/pay.js');

var app = getApp();
Page({
  data: {
    status: false,
    trade_sn: ''
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.setData({
      trade_sn: wx.getStorageSync('trade_sn'),
      status: options.status
    })
    this.updateSuccess()
  },
  onReady: function() {

  },
  onShow: function() {
    // 页面显示

  },
  onHide: function() {
    // 页面隐藏

  },
  onUnload: function() {
    // 页面关闭

  },

  updateSuccess: function() {
    let that = this
    util.request(api.OrderQuery, {
      trade_sn: that.data.trade_sn
    }).then(function(res) {})
  },

  requestPayParam() {
    let that = this;

    util.request(api.WXPayPrepayId, {
      trade_sn: that.data.trade_sn,
      openid: app.globalData.token
    }, 'GET').then(function(res) {
      console.log(res);
      if (res.state === 1) {
        wx.requestPayment({
          'timeStamp': res.timeStamp,
          'nonceStr': res.nonceStr,
          'package': res.package,
          'signType': res.signType,
          'paySign': res.paySign,
          'success': function(res) {
            wx.setStorageSync('trade_sn', trade_sn);
            wx.redirectTo({
              url: '/pages/payResult/payResult?status=true',
            })
          },
          'fail': function(res) {
            wx.redirectTo({
              url: '/pages/payResult/payResult?status=false',
            })
          }
        })
      }
    });
  },
  payOrder() {
    this.requestPayParam();
  },
})